/**
 * Created by dh.huang on 2016/8/29.
 */
angular.module('inspinia')
  .controller('settingCtrl',function ($scope,$rootScope,toaster,$http, fileReader, getUrl,roles) {
    $scope.userdata = JSON.parse(window.localStorage.getItem('user'));
    $scope.loginUser = JSON.parse(localStorage["loginUser"]);

    $scope.pages = roles[$scope.loginUser.role].menus;
    if($scope.userdata.birthday =='' ||$scope.userdata.birthday == undefined){
      $scope.userdata.birthday = new Date();
    }
console.log($scope.userdata );
      var userid = window.localStorage.getItem('userid');
      var args = getUrl('userid', window.location.href);
      if (args != '') {
        userid = args;
      }

      //隐私设置
      function parseMessageData(data) {
        try {
          var message = JSON.parse(data);
          return message;
        } catch (e) {
          return false;
        }
      }

      $scope.checkThis = function (type) {
        //console.log($event.target);
        if (type == 1) {
          angular.element("#private-isDicom").attr("checked", true);
          angular.element("#private-isJpg").attr("checked", false);
        }
        if (type == 2) {
          angular.element("#private-isDicom").attr("checked", false);
          angular.element("#private-isJpg").attr("checked", true);
        }
      }
      $http.get($rootScope.servers + "/service/user/" + userid + "/privacy")
        .success(function (data) {
          var result = data.result;
          if (result == 0) {
            var message = parseMessageData(data.message);
            $scope.initHeadPicFile = data.message[0].headpicfile == '' ? true : false;
            $scope.initCardFile = data.message[0].cardfile == '' ? true : false;
            $scope.initCertFile = data.message[0].certfile == '' ? true : false;
            $scope.initSignFile = data.message[0].signarturefile == '' ? true : false;
            $scope.set = message[0];
          }
        })
      $scope.updatePrivate = function () {
        var data = {};
        data = $scope.set;
        $http.post($rootScope.servers + "/service/user/updateprivacy", data)
          .success(function (data) {
            var result = data.result;
            if (result == 0) {
              toaster.pop({
                type: 'success',
                title: '设置成功',
                showCloseButton: true,
                timeout: 2200
              });
            } else if (result == -1) {
              toaster.pop({
                type: 'error',
                body: '设置失败',
                showCloseButton: true,
                timeout: 2200
              });
            } else {
              toaster.pop({
                type: 'error',
                body: '未知错误',
                showCloseButton: true,
                timeout: 2200
              });
            }
          })
          .error(function () {
            toaster.pop({
              type: 'error',
              body: '服务器异常',
              showCloseButton: true,
              timeout: 2200
            });
          })
      }
      //个人信息管理
      $scope.getFile = function () {
        fileReader.readAsDataUrl($scope.$$childHead.$$childHead.file, $scope)
          .then(function (result) {
            $scope.imageSrc = result;
          });
      };
      $scope.selectImg = function () {
        $("#imgOne").click();
      }
      $scope.selectImg2 = function () {
        $("#img2").click();
      }
      $scope.selectImg3 = function () {
        $("#img3").click();
      }
      $scope.selectImg4 = function () {
        $("#img4").click();
      }
      $scope.openFile = function (loginServer) {
        // angular.element("#myfile").click();
        if (loginServer == 0) {
          angular.element("#myfile").click();
        }
        if (loginServer == 1) {
          angular.element("#myfile2").click();
        }
        if (loginServer == 2) {
          angular.element("#myfile4").click();
        }
        if (loginServer == 3) {
          angular.element("#myfile6").click();
        }
      }
      $scope.imageShow = function () {
        angular.element("#replaceimage").hide();
      }
      //init message
      $http.get($rootScope.servers + "/service/user/" + userid)
        .success(function (data) {
          var result = data.result;
          if (result == 0) {
            var message = parseData(data.message);
            if (message) {
              $("#userdetail-userid").val(userid);
              $("#pre_province").val(message[0].province);
              $("#pre_city").val(message[0].city);
              $("#pre_district").val(message[0].area);
              $scope.userdata = message[0];
              if (message[0].birthday) {
                $scope.userdata.birthday = message[0].birthday.substr(0, 4) + '-' + message[0].birthday.substr(4, 2) + '-' + message[0].birthday.substr(6, 2);
              }else {
                $scope.userdata.birthday=moment().format('YYYY-MM-DD');
              }

              if (message[0].status == 1) {
                angular.element("#update-data-btn").html('提交审核');
                $scope.status4 = true;
              } else if (message[0].status == 2) {
                angular.element("#update-data-btn").html('正在审核中');
                $scope.status2 = true;
              } else if (message[0].status == 3) {
                angular.element("#examine").html('您提交用户资料申请审核不通过，原因是：' + message[0].reason + '，请完善资料后重新提交申请');
                $("#examine").show();
              } else if (message[0].status == 5) {
                angular.element("#examine").html('用户帐号被冻结，请联系客服处理。');
                $("#examine").show();
              } else {
                angular.element("#update-data-btn").html('确认更新');
                $scope.status4 = true;
              }

              var citySelector;
              $(function () {
                citySelector = function () {
                  var province = $("#userdetail-province");
                  var city = $("#userdetail-city");
                  var district = $("#userdetail-area");
                  var preProvince = $("#pre_province");
                  var preCity = $("#pre_city");
                  var preDistrict = $("#pre_district");
                  var jsonProvince = "../js/content/json-array-of-province.js";
                  var jsonCity = "../js/content/json-array-of-city.js";
                  var jsonDistrict = "../js/content/json-array-of-district.js";
                  var hasDistrict = true;
                  var initProvince = "<option value='0'>请选择省份</option>";
                  var initCity = "<option value='0'>请选择城市</option>";
                  var initDistrict = "<option value='0'>请选择区县</option>";
                  return {
                    Init: function () {
                      var that = this;
                      that._LoadOptions(jsonProvince, preProvince, province,
                        null, 0, initProvince);
                      province.change(function () {
                        that._LoadOptions(jsonCity, preCity, city, province, 2,
                          initCity);
                      });
                      if (hasDistrict) {
                        city.change(function () {
                          that._LoadOptions(jsonDistrict, preDistrict,
                            district, city, 4, initDistrict);
                        });
                        province.change(function () {
                          city.change();
                        });
                      }
                      province.change();
                    },
                    _LoadOptions: function (datapath, preobj, targetobj, parentobj, comparelen, initoption) {
                      $.get(datapath,
                        function (r) {
                          var t = ''; // t: html容器
                          var s; // s: 选中标识
                          var pre; // pre: 初始值
                          if (preobj == undefined) {
                            pre = 0;
                          } else {
                            pre = preobj.val();
                          }
                          for (var i = 0; i < r.length; i++) {
                            s = '';
                            if (comparelen === 0) {
                              if (pre !== "" && pre !== 0 && r[i].code === pre) {
                                s = ' selected=\"selected\" ';
                                pre = '';
                              }
                              t += '<option value=' + r[i].code + s + '>' + r[i].name + '</option>';
                            } else {
                              var p = parentobj.val();
                              if (p.substring(0, comparelen) === r[i].code.substring(0, comparelen)) {
                                if (pre !== "" && pre !== 0 && r[i].code === pre) {
                                  s = ' selected=\"selected\" ';
                                  pre = '';
                                }
                                t += '<option value=' + r[i].code + s + '>' + r[i].name + '</option>';
                              }
                            }
                          }
                          if (initoption !== '') {
                            targetobj.html(initoption + t);
                          } else {
                            targetobj.html(t);
                          }
                          targetobj.selectpicker('refresh');
                        }, "json");
                    }
                  };
                }();
                citySelector.Init();
              });
            }
          }
        })
      //update message
      $scope.updateUser = function () {
        var formData = new FormData($("#userdetail-form")[0]);
        //var formData = new FormData();
        var birthday = $("#userdatabirthday").val();
        if (birthday) {
          var birthday = birthday.substr(0, 4) + birthday.substr(5, 2)
            + birthday.substr(8, 2);
          formData.append('birthday', birthday);
        }
        $scope.userdata.headpic = $('#imgPre').attr('src');
        $scope.userdata.signature = $('#imgPre4').attr('src');
/*

        if (document.getElementById("imgOne").getAttribute("bChanged") == "false" && $scope.initHeadPicFile) {
          formData.delete("headpicfile");
        }

        if (document.getElementById("img2").getAttribute("bChanged") == "false" && $scope.initCardFile) {
          formData.delete("cardfile", '');
        }

        if (document.getElementById("img3").getAttribute("bChanged") == "false" && $scope.initCertFile) {
          formData.delete("certfile", '');
        }
*/

        if (document.getElementById("img4").getAttribute("bChanged") == "false" && $scope.initSignFile) {
          formData.delete("signaturefile", '');
        }

        var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        //var reg_phone = //;
        var reg_phone = /^(0\d{2}-?\d{8}|0\d{3}-?\d{7})$/;
        var reg_moile = /^[1][3,4,5,7,8][0-9]{9}$/;
        if ($scope.userdata.gender == undefined || $scope.userdata.gender == '') {
          toaster.pop({
            type: 'warning',
            title: '请选择性别',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        } else if ($scope.userdata.birthday == '' || $scope.userdata.birthday == undefined) {
          toaster.pop({
            type: 'warning',
            title: '生日不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        } else if ($scope.userdata.mobile !=undefined && $scope.userdata.mobile != ''  && !reg_moile.test($scope.userdata.mobile)) {
          toaster.pop({
            type: 'warning',
            title: '手机格式不正确',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }
        else if ($scope.userdata.mobile !=undefined && $scope.userdata.phone != ''  && !reg_phone.test($scope.userdata.phone)) {
          toaster.pop({
            type: 'warning',
            title: '电话格式不正确',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }
        else if (!reg.test($scope.userdata.email)) {//验证邮箱
          toaster.pop({
            type: 'warning',
            title: '邮箱输入格式错误',
            showCloseButton: true,
            timeout: 2000
          })
          return;
        }
        else if ($scope.userdata.name == '' || $scope.userdata.name == undefined) {
          toaster.pop({
            type: 'warning',
            title: '真实姓名不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }
        /*else if ($scope.userdata.province == 0 || $scope.userdata.hospital == '' || $scope.userdata.hospital == undefined) {
          toaster.pop({
            type: 'warning',
            title: '所在医院地址不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }*/
        else if ($scope.userdata.department == '' || $scope.userdata.department == undefined) {
          toaster.pop({
            type: 'warning',
            title: '科室名不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }
        else if ($scope.userdata.title == '' || $scope.userdata.title == undefined) {
          toaster.pop({
            type: 'warning',
            title: '医师职称不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }
      /*  else if ($scope.userdata.post == '' || $scope.userdata.post == undefined) {
          toaster.pop({
            type: 'warning',
            title: '高校职务不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }*/
        else if ($scope.userdata.skilled == '' || $scope.userdata.skilled == undefined) {
          toaster.pop({
            type: 'warning',
            title: '擅长不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }
 /*       else if ($scope.userdata.experience == '' || $scope.userdata.experience == undefined) {
          toaster.pop({
            type: 'warning',
            title: '职业经历不能为空',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }*/
        else if($scope.userdata.signature == '' || $scope.userdata.signature == undefined){
          toaster.pop({
            type: 'warning',
            title: '请上传签名',
            showCloseButton: true,
            timeout: 2200
          });
          return false;
        }

        window.localStorage.setItem('user',JSON.stringify($scope.userdata));
        toaster.pop({
          type: 'success',
          title: '信息更新成功',
          showCloseButton: true,
          timeout: 2000
        })
       /* $.ajax({
          url: $rootScope.servers + '/service/user/update',
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          success: function (data) {
            data = JSON.parse(data);
            var result = data.result;
            if (result == 0) {
              toaster.pop({
                type: 'success',
                title: '信息更新成功',
                showCloseButton: true,
                timeout: 2000
              })
              document.getElementById("imgOne").setAttribute("bChanged", false);
              document.getElementById("img2").setAttribute("bChanged", false);
              document.getElementById("img3").setAttribute("bChanged", false);
              document.getElementById("img4").setAttribute("bChanged", false);
              $scope.initSignFile = true;
              $scope.initCertFile = true;
              $scope.initCardFile = true;
              $scope.initHeadPicFile = true;
            } else if (result == -1) {
              toaster.pop({
                type: 'error',
                title: '信息更新失败',
                showCloseButton: true,
                timeout: 2000
              })
              $scope.initSignFile = false;
              $scope.initCertFile = false;
              $scope.initCardFile = false;
              $scope.initHeadPicFile = false;
            } else {
              toaster.pop({
                type: 'error',
                title: '服务器异常',
                showCloseButton: true,
                timeout: 2000
              })
              $scope.initSignFile = false;
              $scope.initCertFile = false;
              $scope.initCardFile = false;
              $scope.initHeadPicFile = false;
            }

          }
        });*/
      }
      //密码
      $scope.updatePass = function () {
        var password = $("#password").val();
        var newpass = $("#newpass").val();
        var rpassword = $("#rpassword").val();
        if (newpass != rpassword) {
          toaster.pop({
            type: 'error',
            body: '两次密码输入不相同',
            showCloseButton: true,
            timeout: 2200
          });
        } else {
          var _user = JSON.parse(window.localStorage.getItem('user'));
          _user.password = newpass;
          window.localStorage.setItem('user',JSON.stringify(_user));
          toaster.pop({
            type: 'success',
            body: '修改密码成功',
            showCloseButton: true,
            timeout: 2200
          });
/*          $http.post($rootScope.servers + "/service/user/updatepassword", {
            'userid': userid,
            'password': password,
            'newpass': newpass
          })
            .success(function (data) {
              var result = data.result;
              if (result == 0) {
                toaster.pop({
                  type: 'success',
                  body: '修改密码成功',
                  showCloseButton: true,
                  timeout: 2200
                });
              } else if (result == 1) {
                toaster.pop({
                  type: 'error',
                  body: '用户不存在',
                  showCloseButton: true,
                  timeout: 2200
                });
              } else if (result == 2) {
                toaster.pop({
                  type: 'error',
                  body: '密码错误',
                  showCloseButton: true,
                  timeout: 2200
                });
              } else if (result == -1) {
                toaster.pop({
                  type: 'error',
                  body: '修改密码失败',
                  showCloseButton: true,
                  timeout: 2200
                });
              } else {
                toaster.pop({
                  type: 'error',
                  body: '未知错误',
                  showCloseButton: true,
                  timeout: 2200
                });
              }
            })
            .error(function () {
              toaster.pop({
                type: 'error',
                body: '服务器异常',
                showCloseButton: true,
                timeout: 2200
              });
            })*/
        }
      }
      //
      var dataDefine = {
        userid: userid
      }
/*      $http.post($rootScope.servers + '/service/user/getCustom', dataDefine, {
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: transform
      })
        .success(function (data) {
          $scope.consultData = data.message[0];
        })*/
      $scope.defineReport = function () {

        //var reg = /^(\(\d{3,4}\)|\d{3,4})?\d{7,15}$/;
        var strRegex = "^((https|http|ftp|rtsp|mms)://)?[a-z0-9A-Z]{3}\.[a-z0-9A-Z][a-z0-9A-Z]{0,61}?[a-z0-9A-Z]\.com|net|cn|cc (:s[0-9]{1-4})?/$";
        var RegUrl = new RegExp(strRegex);
        if ($("#tel").val() == null) {
          toaster.pop({
            type: 'error',
            body: '您输入的服务热线有误',
            showCloseButton: true,
            timeout: 2200
          });
        } else if ($("#hospital").val().match(RegUrl) == null) {
          toaster.pop({
            type: 'error',
            body: '您输入的网站有误',
            showCloseButton: true,
            timeout: 2200
          });
        } else {
          var data = {
            ask_report_title: $("#title").val(),
            ask_report_subtitle: $("#subtitle").val(),
            image_report_title: $("#etitle").val(),
            image_report_subtitle: $("#esubtitle").val(),
            server_hotline: $("#tel").val(),
            server_platform: $("#rangename").val(),
            server_site: $("#hospital").val(),
            userid: userid
          }
          $http.post($rootScope.servers + '/service/user/custom', data, {
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            transformRequest: transform
          })
            .success(function (data) {
              if (data.result == 0) {
                toaster.pop({
                  type: 'success',
                  body: '自定义成功',
                  showCloseButton: true,
                  timeout: 2200
                });
              }
            })
        }
      }
  });
